<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-14 11:19:38
 * @version $Id$
 */

namespace app\mall\controller;

use think\Db;
use think\Request;
use think\Config;
use think\Controller;

class Brand extends Controller {

	/**
	 * 返回商品列表
	 * @return [type] [description]
	 */
	function index(){
		$list = Db::name('goods_brand')->order('brand_sort desc')->where(['brand_status'=>1])->select();
		$tmp = [];$return_data = [];
		foreach ($list as $k => $v) {
			$tmp[$v['brand_firstchar']][] = $v;
		}

		foreach ($tmp as $key => $value) {
			$return_data[] = [
				'name' => $key,
				'list' => $value
			];
		}
		$this->success('success','',$return_data);
	}

	/**
	 * 根据商品所属分类查出品牌
	 * @return [type] [description]
	 */
	function cateBrand(){
		$param = Request()->param();
		!$param['cate_id'] && $this->error('参数错误');
		$cate_id = $param['cate_id'];

		$cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');
		$cate_ids = implode(',',array_column($cat->getChildren($cate_id),'cate_id'));

		$list  = Db::field('b.*')
		->table('sdzx_goods')->alias('g')
		->join('sdzx_goods_brand b','g.brand_id=b.brand_id')
		->where("g.category_id in ({$cate_ids})")
		->group('b.brand_id')
		->select();

		$this->success('success','',$list);
	}

	// 点击
	public function brandClick(){
		$param = Request()->param();
		$brand_id = $param['brand_id']?:0;

		$goods = Db::table('sdzx_goods')->alias('g')
    	->field('g.goods_id,g.goods_name,g.brand_name,g.brand_id,g.unit,g.category_id,g.keywords,g.introduction,g.sort,g.label_id,g.picture,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,min(sval.sellout) as goods_sellout,max(sval.is_recommend) as is_recommend,max(sval.is_new) as is_new,max(sval.is_cutprice) as is_cutprice,sum(sval.sales) as sales, max(sval.is_hot) as  is_promotion ')
    	->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
    	->where("sval.status=1 and g.brand_id = $brand_id")
    	->group('g.goods_id')
    	->select();

		//商品规格
		foreach ($goods as $k => $v) {
    		$tmp = Db::connect([],'sval')->name('goods_specval')->where(['goods_id'=>$v['goods_id'],'status'=>1])->order('price asc')->select();
    		$unit = $v['unit'];
            // $cur = array_shift($tmp);
            $goods[$k] = array_merge($goods[$k],$tmp[0]);
            if (sizeof($tmp)>1) {
                $goods[$k]['list']=$tmp;
                $goods[$k]['unit']=$unit;
            }
    	}

    	$this->success('success','',['list'=>$goods]);
	}

}